# -*-coding:utf-8-*-
'''

'''
import pandas as pd
import numpy as np
from pandas import DataFrame, Series
from sklearn.cluster import KMeans
from sklearn.cluster import Birch


# 读取文件，转成df
def get_from_file(path):
    # data = pd.read_csv(path)
    data = pd.read_table(path, sep=',')
    return DataFrame(data)


'''
聚类算法
'''


def kmeans_cluster(data):
    mod = KMeans(n_clusters=3, n_jobs=4, max_iter=500)  # 聚成3类数据,并发数为4，最大循环次数为500
    mod.fit_predict(data)  # y_pred表示聚类的结果
    # 聚成3类数据，统计每个聚类下的数据量，并且求出他们的中心
    r1 = pd.Series(mod.labels_).value_counts()
    r2 = pd.DataFrame(mod.cluster_centers_)
    result = pd.concat([r2, r1], axis=1)
    result.columns = list(data.columns) + [u'类别数目']
    print(result)
    # 给每一条数据标注上被分为哪一类
    result = pd.concat([data, pd.Series(mod.labels_, index=data.index)], axis=1)
    result.columns = list(data.columns) + [u'聚类类别']
    print(result.head(100))
    # r.to_excel(outfile)  # 如果需要保存到本地，就写上这一列
    return result


def picture(result):
    # 可视化过程
    from sklearn.manifold import TSNE
    ts = TSNE()
    ts.fit_transform(result)
    ts = pd.DataFrame(ts.embedding_, index=result.index)
    import matplotlib.pyplot as plt
    a = ts[result[u'聚类类别'] == 0]
    plt.plot(a[0], a[1], 'r.')
    a = ts[result[u'聚类类别'] == 1]
    plt.plot(a[0], a[1], 'go')
    a = ts[result[u'聚类类别'] == 2]
    plt.plot(a[0], a[1], 'b*')
    plt.show()


if __name__ == "__main__":
    #     path = 'data/Titanic/train.csv'
    path = u'F:\hxfile\chromeDownload\Basketball\\basketball.dat'
    source_data = get_from_file(path)
    #     print(source_data.head())
    #     print(type(source_data))
    # print(source_data)
    result = kmeans_cluster(source_data)
    picture(result)